package com.caissa.framework.starter.autoconfigure.instrument.aop.ltw;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * Description:
 * User: forest
 * Date: 2021-01-12 11:25 上午
 */
@Aspect
public abstract class HttpClientAspect extends AspectLTWBase {

    @Override
    public String getMetricName(ProceedingJoinPoint pjp){
        try {
            String name = pjp.getSignature().toLongString();
            Object targetMethod = ((MethodSignature) pjp.getSignature()).getMethod().getName();

            if (name.contains("org.apache.http.impl.conn.PoolingHttpClientConnectionManager")) {
                return "getConnFromPool(socket maybe closed)";
            }else if(name.contains("org.apache.http.protocol.HttpRequestExecutor")) {
                return "transferReqRespOverConn(BIO)";
            }else if(name.contains("org.apache.http.impl.execchain.RetryExec")) {
                return "RetryExec";
            }else if(name.contains("org.apache.http.impl.execchain.ProtocolExec")) {
                return "ProtocolExec";
            }else if(name.contains("org.apache.http.impl.execchain.MainClientExec")) {
                if (targetMethod.equals("establishRoute")) {
                    return "establishSocket2Server(Route)";
                }
                return "MainClientExec";
            } else if (name.contains("org.apache.http.impl.conn.SystemDefaultDnsResolver")
                    || name.contains("org.apache.http.impl.conn.InMemoryDnsResolver")) {
                return "DnsResolver";
            } else if (name.contains("org.apache.http.protocol.ImmutableHttpProcessor")) {
                Object[] args = pjp.getArgs();
                if (args != null && args.length > 0) {
                    if (HttpRequest.class.isAssignableFrom(pjp.getArgs()[0].getClass())) {
                        return "Pre_interceptors";
                    } else if (HttpResponse.class.isAssignableFrom(pjp.getArgs()[0].getClass())) {
                        return "Post_interceptors";
                    }
                }
            } else if (name.contains("org.apache.http.impl.client.InternalHttpClient")) {
                return "HighLevelMain";
            }
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return "HttpClientAspect getMetricName fail";
        }
    }

    @Override
    protected String getMetricType() {
        return "HttpClient";
    }
}
